//
//  CityHunterTableViewController.m
//  Travelmemory
//
//  Created by lanou3g on 16/4/2.
//  Copyright © 2016年 ABCD. All rights reserved.
//

#import "CityHunterTableViewController.h"
#import "TravelHelper.h"
#import "CityHunterTableViewCell.h"
#import "CityHunterModel.h"
#import "UIImageView+WebCache.h"
@interface CityHunterTableViewController ()

/** 用户解析时保存数据使用 */
@property (nonatomic ,strong) NSMutableArray *dataArray;

/** 用于上拉加载使用 */
@property (nonatomic, assign) NSInteger start;  //  城市的url后面的编码

@property (nonatomic ,strong) UIImage *naimage;

@property (nonatomic ,strong) UIButton  *but; // 显示城市按钮

@property (nonatomic ,strong) UIButton *butimage; // 收起按钮

@property (nonatomic ,strong) NSString *cityUrl;

@end

@implementation CityHunterTableViewController



-(void)viewWillAppear:(BOOL)animated{
    
    self.tabBarController.tabBar.hidden = NO;
    

}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.start = 0;
    self.view.backgroundColor = [UIColor orangeColor];
    self.dataArray = [NSMutableArray array];
    
    self.navigationItem.title = @"城市猎人带你玩";
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor blackColor],NSFontAttributeName:[UIFont systemFontOfSize:19]}];

    
    // 注册
    [self.tableView  registerClass:[CityHunterTableViewCell class] forCellReuseIdentifier:@"cell"];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navigationBar"] forBarMetrics:UIBarMetricsDefault];
    
    // 导航栏左button
    UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 110, 20)];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:view];
    
    self.butimage = [UIButton buttonWithType:UIButtonTypeCustom];
    self.butimage.frame = CGRectMake(0, 0, 25, 20);
    [self.butimage setBackgroundImage:[UIImage imageNamed:@"shouqi"] forState:(UIControlStateNormal)];
    [view addSubview:self.butimage];
    
    [self.butimage addTarget:self action:@selector(changeCity:) forControlEvents:(UIControlEventTouchUpInside)];
    
    _but = [UIButton buttonWithType:UIButtonTypeCustom];
    // 让button的文本居左
    _but.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    _but.frame = CGRectMake(CGRectGetMaxX(_butimage.frame), 0, 90, 20);
    [view addSubview:_but];
    
    // 给button添加一个方法
    [_but addTarget:self action:@selector(changeCity:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [_but setTitle:@"北京" forState:(UIControlStateNormal)];
    [self.but setTitleColor:[UIColor blackColor] forState:(UIControlStateNormal)];

    //  解析数据
    NSString *str = @"http://api.breadtrip.com/hunter/products/more/?city_name=%E5%8C%97%E4%BA%AC&start=0";
    
    // 第一次进入页面,显示北京的内容
    [self resolveData:str];


}

#pragma mark ---- 解析数据
-(void)resolveData:(NSString *)urlStr
{
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [[TravelHelper defaultTravelHelper]get:urlStr params:nil success:^(id responseObj) {
        
        for (NSDictionary *dic in responseObj[@"product_list"]) {
            
            CityHunterModel *model = [[CityHunterModel alloc]init];
            
            [model setValuesForKeysWithDictionary:dic];
            
            // 把解析出来的二级内容也赋值给m
            [model setValuesForKeysWithDictionary:dic[@"user"]];
            
            [self.dataArray addObject:model];
            
            
        }
        
//        // 结束刷新
//        [self.tableView.header endRefreshing];
//        [self.tableView.footer endRefreshing];
        
        self.tableView.separatorStyle = UITableViewCellSeparatorStyleSingleLine;
        
//        [GiFHUD dismiss];
        // 更新数据
        [self.tableView reloadData];
        
    } failure:^(NSError *error) {
//        // 结束刷新
//        [self.tableView.header endRefreshing];
//        [self.tableView.footer endRefreshing];
//        UIAlertView *view = [[UIAlertView alloc]initWithTitle:@"系统提示" message:@"网络链接失败,请查看网络连接" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil, nil];
        
//        [view show];
//        [GiFHUD dismiss];
    }];
    
}
#pragma mark  -- 刷新方法
//- (void)upChangeData {
//    NSString *cityUrl = [SingleHelper defaultHunterCityHelper].aString;
//    
//    self.start = 0;
//    NSString *s = @"http://api.breadtrip.com/hunter/products/more/?city_name=%E5%8C%97%E4%BA%AC&start=";
//    // 北京的url
//    NSString *str = [NSString stringWithFormat:@"%@%d",s, self.start];
//    
//    // 第一次进入页面,显示北京的内容
//    if (cityUrl == nil) {
//        cityUrl = str;
//    }
//    [[CDHttpHelper defaultCDHttpHelper]get:cityUrl params:nil success:^(id responseObj) {
//        [self.dataArray removeAllObjects];
//        for (NSDictionary *dic in responseObj[@"product_list"]) {
//            CityHunterModel *m = [[CityHunterModel alloc]init];
//            [m setValuesForKeysWithDictionary:dic];
//            
//            // 把解析出来的二级内容也赋值给m
//            [m setValuesForKeysWithDictionary:dic[@"user"]];
//            
//            [self.dataArray addObject:m];
//            
//        }
//        
//        // 结束刷新
//        [self.tableView.header endRefreshing];
//        [self.tableView.footer endRefreshing];
//        
//        [GiFHUD dismiss];
//        // 更新数据
//        [self.tableView reloadData];
//        
//    } failure:^(NSError *error) {
//        // 结束刷新
//        [self.tableView.header endRefreshing];
//        [self.tableView.footer endRefreshing];
//        [GiFHUD dismiss];
//        NSLog(@"CityHunter解析错误提示:%@",error);
//    }];
//    
//}
//
//- (void)downChageData {
//    
//    
//    self.start =self.start + 20;
//    
//    NSString *cityUrl = [SingleHelper defaultHunterCityHelper].aString;
//    
//    NSString *str = @"http://api.breadtrip.com/hunter/products/more/?city_name=%E5%8C%97%E4%BA%AC";
//    
//    // 第一次进入页面,显示北京的内容
//    if (cityUrl == nil) {
//        [self resolveData:[NSString stringWithFormat:@"%@&start=%d", str,self.start]];
//    }else{
//        if (self.dataArray.count != 0) {
//            // [self.dataArray removeAllObjects];
//        }
//        [self resolveData:[NSString stringWithFormat:@"%@&start=%d", cityUrl,self.start]];
//        //  [self resolveData:cityUrl];
//    }
//}






- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {

    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {

    return self.dataArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CityHunterTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    
    cell.accessoryType = UITableViewCellAccessoryNone;
    
//        防止cell重用问题,本来就从重用池里拿了label放到myview上,但是又在下面重新创建了label,所以就重复了,解决方法:把myview上已经存在的label先移除掉,再从重用池里拿label
    [cell.Myview.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    
    CityHunterModel *cityMode = self.dataArray[indexPath.row];
    
    // 赋值
    cell.TitleLabel.text = cityMode.title;
    cell.TimeLabel.text = cityMode.date_str;
    cell.AdressLabel.text = cityMode.address;
    cell.LikeCountLabel.text =  cityMode.like_count;
    cell.PriceLabel.text = cityMode.price;
    
    cell.TimeAddress.text = [NSString stringWithFormat:@"%@ • %@ • %@人喜欢", cityMode.date_str,cityMode.address, cityMode.like_count];
    
    // 标题图片
    [cell.MainImage sd_setImageWithURL:[NSURL URLWithString:cityMode.title_page] placeholderImage:[UIImage imageNamed:@"cat"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
    }];
    
    // 用户图片
    [cell.UserImage sd_setImageWithURL:[NSURL URLWithString:cityMode.avatar_l] placeholderImage:[UIImage imageNamed:@"cat"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
    }];
    
    
    // 标签
    CGFloat x = 0; // 记录第一行label最大的x值
    CGFloat y = 0; // 保存第一行超出屏幕边界那个label的下标
    CGFloat z = 0; // 记录第二行label最大的x值
    
    for (int i = 0; i< cityMode.tab_list.count; i++) {
        
        // 标签
        UILabel *BiaoQianLabel = [[UILabel alloc]init];
        
        
        // 自适应label的宽度
        
        NSString *String = cityMode.tab_list[i];
        BiaoQianLabel.text = String;
        UIFont *font = [UIFont systemFontOfSize:14];
        BiaoQianLabel.font = font;
        BiaoQianLabel.textColor = [UIColor grayColor];
        //        BiaoQianLabel.layer.borderColor = [[UIColor grayColor]CGColor];
        //        BiaoQianLabel.layer.borderWidth = 1.0;
        
        // 设置label的最大宽度和高度
        CGSize size = CGSizeMake(self.view.bounds.size.width - 110, 100);
        
        // 获取当前文本的属性
        NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil];
        
        // 获取文本需要的size,限制宽度
        CGSize Actualsize = [String boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
        
        BiaoQianLabel.frame = CGRectMake(20 + x , 5,Actualsize.width , Actualsize.height);
        x = CGRectGetMaxX(BiaoQianLabel.frame);
        [cell.Myview addSubview:BiaoQianLabel];
        if (x > self.view.bounds.size.width - 110) {
            y = i;
            // 移除超出屏幕范围的label
            [BiaoQianLabel removeFromSuperview];
            break;
        }
    }
    if (y <= cityMode.tab_list.count && x > self.view.bounds.size.width - 110) {
        
        for (int i = y ; i < cityMode.tab_list.count; i ++) {
            
            UILabel *BiaoQianLabel = [[UILabel alloc]init];
            
            NSString *String = cityMode.tab_list[i];
            BiaoQianLabel.text = String;
            UIFont *font = [UIFont systemFontOfSize:14];
            BiaoQianLabel.font = font;
            BiaoQianLabel.textColor = [UIColor grayColor];
            
            // 设置label的最大宽度和高度
            CGSize size = CGSizeMake(300, 100);
            
            // 获取当前文本的属性
            NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil];
            
            // 获取文本需要的size,限制宽度
            CGSize Actualsize = [String boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
            z = CGRectGetMaxX(BiaoQianLabel.frame);
            BiaoQianLabel.frame = CGRectMake(20 + z , 25,Actualsize.width , Actualsize.height);
            
            
            [cell.Myview addSubview:BiaoQianLabel];
            
        }
    }

    
    
    return cell;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    
    return 330;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
